import 'package:flutter/cupertino.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/profile/models/model_question_items.dart';
import 'package:flutter_09_game/pages/profile/profile_safety_center/profile_safety_center_logic.dart';
import 'package:flutter_09_game/pages/profile/profile_safety_center/profile_safety_center_view.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:get/get.dart';

class ProfileSetPasswordLogic extends BaseController {
  List<ModelQuestionItems> questionItems = [];
  RxString questionRx = ''.obs;

  TextEditingController answerController = TextEditingController();
  TextEditingController tipsController = TextEditingController();

  // 资金密码相关
  RxString fundPassword = ''.obs;
  RxString confirmPassword = ''.obs;
  RxBool isFormValid = false.obs;

  @override
  void onInit() {
    super.onInit();
    _setupValidation();
    executeInitMethod(getQuestionItems);
// clog('dalsdjlaskdj');
  }

  /// 设置表单验证监听
  void _setupValidation() {
    // 监听所有字段变化，实时验证表单
    everAll([
      questionRx,
      fundPassword,
      confirmPassword,
    ], (val) {
      clog('dasdasdasd');
      _validateForm();
    });

    // 监听文本控制器变化
    answerController.addListener(_validateForm);
    tipsController.addListener(_validateForm);
  }

  Future getQuestionItems() async {
    HttpResponse response = await HttpManager().get(
      API.getQuestion,
      fromJson: ModelQuestionItems.fromJson,
    );
    if (response.isSuccess) {
      questionItems = response.data;
      questionRx.value = questionItems.firstOrNull?.Content ?? "";
    }
  }

  /// 表单验证
  void _validateForm() {
    final isValid = _isFormComplete() && _isPasswordValid();
    isFormValid.value = isValid;
  }

  /// 检查表单是否完整
  bool _isFormComplete() {
    return questionRx.value.isNotEmpty &&
        answerController.text.trim().isNotEmpty &&
        tipsController.text.trim().isNotEmpty &&
        fundPassword.value.isNotEmpty &&
        confirmPassword.value.isNotEmpty;
  }

  /// 检查密码是否有效
  bool _isPasswordValid() {
    return fundPassword.value.length == 6 && confirmPassword.value.length == 6;
  }

  /// 获取选中问题的ID
  int _getSelectedQuestionId() {
    final selectedQuestion = questionItems.firstWhere(
      (item) => item.Content == questionRx.value,
      orElse: () => questionItems.first,
    );
    return selectedQuestion.id ?? 1;
  }

  /// 设置资金密码
  Future<void> setFundPassword() async {
    if (fundPassword.value != confirmPassword.value) {
      LoadingUtils.showToast(LocaleKeys.enterSameFundPassword.tr);
      return;
    }

    final params = {
      'question_id': _getSelectedQuestionId(),
      'answer': answerController.text.trim(),
      'answer_notice': tipsController.text.trim(),
      'fund_password': fundPassword.value,
      'fund_password_confirm': confirmPassword.value,
    };

    HttpResponse response = await HttpManager().post(
      API.postUserSetFundPassword,
      params: params,
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      AppUserManager().refreshUserInfo();
      if (Get.isRegistered<ProfileSafetyCenterLogic>()) {
        Get.back();
      } else {
        Get.offAndToNamed(AppRoutes.profileSafetyCenterPage);
      }
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    tipsController.dispose();
    answerController.dispose();
  }
}
